package com.geeguo.ebuilder.core.feign.config;

import com.geeguo.ebuilder.core.common.utils.ServletUtils;
import com.geeguo.ebuilder.core.feign.utils.FeignHolder;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 *  Feign 客户端配置
 */
@Configuration
public class FeignConfig implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = ServletUtils.getRequest();
        if (request != null) {
            template.header("X-Real-IP", request.getHeader("X-Real-IP"));
            template.header("X-Forwarded-For", request.getHeader("X-Forwarded-For"));
        } else {
            // 当不存在 ServletRequest 时（如在异步线程中调用）
            Map<String, String> headers = FeignHolder.get();
            if (!headers.isEmpty()) {
                template.header("X-Real-IP", headers.get("x-real-ip"));
                template.header("X-Forwarded-For", headers.get("x-forwarded-for"));
            }
        }
    }

    /**
     * Openfeign调用日志级别
     */
    @Bean
    public Logger.Level feignLoggerLeave(){
        return Logger.Level.BASIC;
    }
}